package com.i2works.smartluolong.web.controller.index;

import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.common.DateUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.Implement.ImplementDO;
import com.i2works.smartluolong.web.entity.Implement.ImplementFilesDO;
import com.i2works.smartluolong.web.entity.Implement.ImplementFilesQuery;
import com.i2works.smartluolong.web.entity.Implement.ImplementQuery;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoDO;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoQuery;
import com.i2works.smartluolong.web.entity.item.ItemAttrDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeQuery;
import com.i2works.smartluolong.web.entity.user.UserAccountExtendDO;
import com.i2works.smartluolong.web.entity.user.UserAccountExtendQuery;
import com.i2works.smartluolong.web.service.implement.IImplementFilesService;
import com.i2works.smartluolong.web.service.implement.IImplementService;
import com.i2works.smartluolong.web.service.item.IItemApasinfoService;
import com.i2works.smartluolong.web.service.item.IItemAttrService;
import com.i2works.smartluolong.web.service.item.IItemNodeService;
import com.i2works.smartluolong.web.service.user.IUserAccountExtendService;
import com.i2works.smartluolong.web.utils.BaseModule;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/unifyDeclare"})
public class UnifyDeclareController extends BaseModule{
	
  private IImplementService implementService;
  private IImplementFilesService implementFilesService;
  private IUserAccountExtendService userAccountExtendService;
  private IItemApasinfoService  itemApasinfoService;
  private IItemAttrService itemAttrService;
  private IItemNodeService  itemNodeService;

  @Autowired
  public UnifyDeclareController(
		  IImplementService implementService, 
		  IImplementFilesService implementFilesService, 
		  IUserAccountExtendService userAccountExtendService,
		  IItemApasinfoService  itemApasinfoService,
		  IItemAttrService itemAttrService,
		  IItemNodeService  itemNodeService)
  {
    this.implementService = implementService;
    this.implementFilesService = implementFilesService;
    this.userAccountExtendService = userAccountExtendService;
    this.itemApasinfoService=itemApasinfoService;
    this.itemAttrService=itemAttrService;
    this.itemNodeService=itemNodeService;
  }

  @GetMapping({"/info/{serviceCode}"})
  public String transact(@PathVariable("serviceCode") String serviceCode, Model model){
    try
    {
      ImplementQuery query = new ImplementQuery();
      query.setServiceCode(serviceCode);
      ImplementDO item = implementService.query(query);
      model.addAttribute("item", item);
      ImplementFilesQuery filesQuery = new ImplementFilesQuery();
      filesQuery.setServiceId(item.getUnid());
      List<ImplementFilesDO> filesList = implementFilesService.queryList(filesQuery);
      model.addAttribute("filesList", filesList);
    } catch (ServiceException e) {
      e.printStackTrace();
    }
    return "unifyDeclare/info";
  }

  @GetMapping({"/handle/{serviceCode}"})
  public String handle(@PathVariable("serviceCode") String serviceCode, Model model){
    try
    {
      ImplementQuery query = new ImplementQuery();
      query.setServiceCode(serviceCode);
      ImplementDO item = implementService.query(query);
      model.addAttribute("item", item);
      ImplementFilesQuery filesQuery = new ImplementFilesQuery();
      filesQuery.setServiceId(item.getUnid());
      List<ImplementFilesDO> filesList = implementFilesService.queryList(filesQuery);
      model.addAttribute("filesList", filesList);
      UserAccountExtendQuery userExtendQuery = new UserAccountExtendQuery();
      userExtendQuery.setUserId(getUserId());
      UserAccountExtendDO userExtend = userAccountExtendService.query(userExtendQuery);
      model.addAttribute("user", getLoginUser());
      model.addAttribute("userExtend", userExtend);
    } catch (ServiceException e) {
      logger.error(e.getMessage());
    }
    return "unifyDeclare/handle";
  }
  
  @PostMapping({"/handle/save"})
  @ResponseBody
  public Result save(ItemApasinfoDO apasinfo,Model model){
	  String projectId=null;
    try
    {
    	projectId=createProjectId(apasinfo.getDeptCode());
    	apasinfo.setProjId(projectId);
    	apasinfo.setProjPwd(createProjectPWD());
    	apasinfo.setApplyCardType("身份证");
    	apasinfo.setContactManCardType("身份证");
    	apasinfo.setApplyFrom("政务服务网");
    	apasinfo.setReceiveTime(new Date());
    	apasinfo.setHandleState("收件");//办理状态
    	apasinfo.setAreaCode("410311");
    	String belongSystem = apasinfo.getAreaCode()+apasinfo.getDeptCode()+"001";
    	apasinfo.setBelongSystem(belongSystem);
    	apasinfo.setCreateName(apasinfo.getApplyName());
    	apasinfo.setUpdateName(apasinfo.getApplyName());
    	apasinfo.setSyncStatus("I");
    	saveAttr(apasinfo.getAttrList(),apasinfo.getProjId());
		 ItemNodeDO  itemNode=new ItemNodeDO();
		 itemNode.setProjId(apasinfo.getProjId());
         itemNode.setAction(apasinfo.getHandleState());
         itemNode.setOpinion("电子件已接收");
         itemNode.setNodeName("收件");
         itemNode.setName(getUserName());
         itemNode.setStartTime(new Date());
         itemNode.setEndTime(new Date());
         itemNode.setBelongSystem(apasinfo.getBelongSystem());
         itemNode.setCreateTime(new Date());
         itemNode.setDataVersion(1);
         itemNode.setNextNodeName("受理");
         itemNode.setAreaCode(apasinfo.getAreaCode());
         itemNode.setHanderDeptId(apasinfo.getDeptCode());
         itemNode.setHanderDeptName(apasinfo.getDeptName());
         itemNode.setPhaseName("申报阶段");
         itemNode.setPhaseCode("01");
         itemNode.setSyncStatus("I");
		 itemNodeService.save(itemNode);
		 apasinfo.setDataVersion(1);
	     apasinfo.setFlowXml(getFlowXML(apasinfo));//流程xml
		 itemApasinfoService.save(apasinfo);
    } catch (ServiceException e) {
      logger.error(e.getMessage());
      return R.error();
    }
    return R.success(projectId);
  }

  @GetMapping({"/receipt/{projectId}"})
  public String receipt(@PathVariable("projectId") String projectId, Model model){
    try
    {
      ItemApasinfoQuery query = new ItemApasinfoQuery();
      query.setProjId(projectId);
      ItemApasinfoDO apasinfo =itemApasinfoService.query(query);
      model.addAttribute("apasinfo", apasinfo);
      ImplementQuery impQuery = new ImplementQuery();
      impQuery.setServiceCode(apasinfo.getServiceCode());
      impQuery.setStatus("Y");
      ImplementDO item =implementService.query(impQuery);
      model.addAttribute("item", item);
    } catch (ServiceException e) {
      logger.error(e.getMessage());
    }
    return "unifyDeclare/receipt";
  }
  
  /**
   * 处理附件
   *
   * @param projectDO 项目
   * @param isUpdate  是否更新项目（更新就先删除以前图片，再新增）
   */
  private void saveAttr(List<String> attrList,String projectId) throws ServiceException {
      if (CollectionUtils.isNotEmpty(attrList)) {
         //删除附件(通过项目ID删除)
         itemAttrService.deleteByProjectId(projectId);
          //添加附件
          for (String attr : attrList) {
        	   String[] str=  attr.split("##");
                  //判断url是否存在
                  String url = StringUtils.isNotBlank(str[0]) ? str[0] : GlobalConstant.NOPIC;
                  //判断文件名是否存在
                  String fileName = StringUtils.isNotBlank(str[1]) ? str[1] : "未命名";
                  //判断附件名是否存在
                  String attrName = StringUtils.isNotBlank(str[2]) ? str[2] : "材料";
                  //写入文件
                  ItemAttrDO attrDO = new ItemAttrDO();
                  attrDO.setCreateName(getUserName());
                  attrDO.setProjId(projectId);
                  attrDO.setAttrName(attrName);
                  attrDO.setFileUrl(url);
                  attrDO.setFileName(fileName);
                  itemAttrService.save(attrDO);
          }
      }
  }
  
  
  /**
   * 
   * 生成办件编号
   * */
  private String createProjectId(String deptCode) {
	  String projId=null;
	  int num=1;
	  try {
		  int length=deptCode.length();
		  String applyDate = DateUtils.get(new Date(), DateConstant.YYMMDD);
		  ItemApasinfoQuery query=new ItemApasinfoQuery();
		  query.setReceiveTime(DateUtils.str2Date(applyDate, DateConstant.YYMMDD));
		  query.setDeptCode(deptCode);
		  num = itemApasinfoService.queryCount(query);
		  num=num+1;
		  projId = "410311" +deptCode.substring(length-3)+ applyDate + '1' + String.format("%06d", num);
	  } catch (ServiceException e) {
		  e.printStackTrace();
	  }
	  return projId;
  }
  
  /**
   * 生成查询密码
   * 
   * */
  private String createProjectPWD() {
	  String sources = "0123456789"; 
		Random rand = new Random();
		StringBuffer flag = new StringBuffer();
		for (int j = 0; j < 6; j++) 
		{
			flag.append(sources.charAt(rand.nextInt(9)) + "");
		}
	  return flag.toString();
  }
  
  /**
   * 生成流程XML
   */
  private String getFlowXML(ItemApasinfoDO apasinfoDO) {
          String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n<NODES>\r\n";
          try {
          List<ItemNodeDO> list=Lists.newArrayList();
          ItemNodeQuery query=new ItemNodeQuery();
          query.setProjId(apasinfoDO.getProjId());
          query.setOrder(0);
          Integer	count = itemNodeService.queryCount(query);
          if(count>0) {
        	  list=itemNodeService.queryList(query);
        	  int step=1;
        	  for (ItemNodeDO itemNodeDO : list) {
                  xml += "<NODE>\r\n" +
                          "    <NODENAME>"+itemNodeDO.getNodeName()+"</NODENAME>\r\n" +
                          "    <STEP>"+step+"</STEP>\r\n" +
                          "    <STATE>"+(4-step)+"</STATE>\r\n" +
                          "    <TIMELIMIT>"+apasinfoDO.getPromiseDays()+"</TIMELIMIT>\r\n"+
                          "    <STARTTIME>"+DateUtils.get(itemNodeDO.getStartTime(), DateConstant.ALL)+"</STARTTIME>\r\n"+
                          "    <ENDTIME>"+DateUtils.get(itemNodeDO.getEndTime(), DateConstant.ALL)+"</ENDTIME>\r\n"+
                          "    <STAYTIME>0</STAYTIME>\r\n"+
                          "    <OPINION>" + itemNodeDO.getOpinion() + "</OPINION>\r\n" +
                          "    <NAME>"+itemNodeDO.getName()+"</NAME>\r\n" +
                          "    <TEL>"+apasinfoDO.getPhone()+"</TEL>\r\n" +
                          "</NODE>\r\n";
                  step++;
			  }
          }
          xml += "</NODES>";
		} catch (ServiceException e) {
			e.printStackTrace();
		}
      return xml;
  }
  


  
}